package com.mk.dynamic.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;
import java.time.Duration;

@Slf4j
public class JedisConnectionFactoryBuilder {

    public static JedisConnectionFactory build(RedisProperties properties) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(properties.getHost());
        redisStandaloneConfiguration.setPort(properties.getPort());
        if (StringUtils.isNotBlank(properties.getPassword())) {
            redisStandaloneConfiguration.setPassword(properties.getPassword());
        }
        if (properties.getDatabase() != 0) {
            redisStandaloneConfiguration.setDatabase(properties.getDatabase());
        }

        //获得默认的连接池构造器
        JedisClientConfiguration.JedisClientConfigurationBuilder builder = JedisClientConfiguration.builder();
        if (properties.getTimeout() != null) {
            // 设置超时时间
            Duration timeout = properties.getTimeout();
            builder.readTimeout(timeout).connectTimeout(timeout);
        }
        // 指定jedisPoolConifig来修改默认的连接池构造器
        RedisProperties.Pool pool = properties.getJedis().getPool();
        if (pool != null) {
            builder.usePooling().poolConfig(poolConfig(properties));
        }
        //通过构造器来构造jedis客户端配置
        JedisClientConfiguration jedisClientConfiguration = builder.build();

        //单机配置 + 客户端配置 = jedis连接工厂
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }


    //连接池配置
    public static JedisPoolConfig poolConfig(RedisProperties properties) {
        RedisProperties.Pool pool = properties.getJedis().getPool();
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(pool.getMaxActive());
        poolConfig.setMaxIdle(pool.getMaxIdle());
        poolConfig.setMinIdle(pool.getMinIdle());
        if (pool.getTimeBetweenEvictionRuns() != null) {
            poolConfig.setTimeBetweenEvictionRunsMillis(pool.getTimeBetweenEvictionRuns().toMillis());
        }
        if (pool.getMaxWait() != null) {
            poolConfig.setMaxWaitMillis(pool.getMaxWait().toMillis());
        }

        return poolConfig;
    }
}
